<script lang="ts" setup>
import { FormSchema, Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { reactive, ref, watch, defineEmits } from 'vue'
import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { Log } from '@/utils/logError'
import { updateUserBasicDataApi } from '@/api/personal-center'

const { t } = useI18n()

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['refresh'])

const { required, phone, maxlength, email } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('personalCenter.name'),
    component: 'Input',
    componentProps: {
      placeholder: t('personalCenter.namePlaceholder')
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'phone',
    label: t('personalCenter.phone'),
    component: 'Input',
    componentProps: {
      placeholder: t('personalCenter.phonePlaceholder')
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'email',
    label: t('personalCenter.email'),
    component: 'Input',
    componentProps: {
      placeholder: t('personalCenter.emailPlaceholder')
    },
    colProps: {
      span: 24
    }
  }
])

const rules = reactive({
  name: [required(), maxlength(50)],
  phone: [required(), phone()],
  email: [required(), email()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getElFormExpose, getFormData } = formMethods

watch(
  () => props.userInfo,
  (value) => {
    setValues(value)
  },
  {
    immediate: true,
    deep: true
  }
)

const saveLoading = ref(false)
const save = async () => {
  const elForm = await getElFormExpose()
  try {
    await elForm?.validate()
    await ElMessageBox.confirm(t('common.confirmSave'), t('common.notice'), {
      confirmButtonText: t('common.save'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    saveLoading.value = true
    const { email, phone, name } = await getFormData()
    const { message } = await updateUserBasicDataApi({ email, phone, name })
    emit('refresh')
    ElMessage.success(message)
    saveLoading.value = false
  } catch (error) {
    Log.error('Modify Personal Information', error)
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <ElDivider />
  <BaseButton type="primary" @click="save">{{ t('common.save') }}</BaseButton>
</template>
